const db = require("@/db/index");

// 分页查询请假申请列表
exports.queryLeave = (req, resp) => {
  try {
    const {
      pageSize = 10,
      pageNum = 1,
      staffName,
      position,
      type,
      audit,
    } = req.body;

    // 构建查询条件
    let conditions = [];
    let params = [];
    if (staffName) {
      conditions.push("staff_name LIKE ?");
      params.push(`%${staffName}%`);
    }
    if (position) {
      conditions.push("position LIKE ?");
      params.push(`%${position}%`);
    }
    if (type) {
      conditions.push("type LIKE ?");
      params.push(`%${type}%`);
    }
    if (audit !== undefined) {
      conditions.push("audit = ?");
      params.push(audit);
    }

    // 组装WHERE子句
    const whereClause =
      conditions.length > 0 ? "WHERE " + conditions.join(" AND ") : "";

    // 查询总数
    const countSql = `SELECT COUNT(*) as total FROM leaveapplication ${whereClause}`;
    db.query(countSql, params, (err, totalResult) => {
      if (err) return resp.err(err);
      const total = totalResult[0].total;

      // 查询数据
      const offset = (pageNum - 1) * pageSize;
      const dataSql = `
                SELECT * FROM leaveapplication 
                ${whereClause} 
                ORDER BY create_time DESC 
                LIMIT ? OFFSET ?
            `;

      db.query(dataSql, [...params, pageSize, offset], (err, rows) => {
        if (err) return resp.err(err);

        resp.ok({
          total,
          list: rows,
          pageSize,
          pageNum,
        });
      });
    });
  } catch (error) {
    resp.err(error);
  }
};

// 新增请假申请
exports.addLeave = (req, resp) => {
  try {
    const leaveInfo = req.body;

    // 验证必填字段
    if (!leaveInfo.staffNo) {
      return resp.err("员工工号不能为空");
    }
    if (!leaveInfo.staffName) {
      return resp.err("员工姓名不能为空");
    }
    if (!leaveInfo.departmentName) {
      return resp.err("部门名称不能为空");
    }
    if (!leaveInfo.position) {
      return resp.err("职位不能为空");
    }
    if (!leaveInfo.type) {
      return resp.err("请假类型不能为空");
    }
    if (!leaveInfo.time) {
      return resp.err("请假时间不能为空");
    }
    if (!leaveInfo.days) {
      return resp.err("请假天数不能为空");
    }

    // 构建插入数据
    const insertData = {
      staff_no: leaveInfo.staffNo,
      staff_name: leaveInfo.staffName,
      department_name: leaveInfo.departmentName,
      position: leaveInfo.position,
      type: leaveInfo.type,
      time: leaveInfo.time,
      days: leaveInfo.days,
      reason: leaveInfo.reason || null,
    };

    // 插入请假申请数据
    const insertSql = "insert into leaveapplication set ?";
    db.query(insertSql, insertData, (err, result) => {
      if (err) {
        console.error("添加请假申请失败:", err);
        return resp.err("添加请假申请失败: " + err.message);
      }
      if (result.affectedRows !== 1) {
        return resp.err("添加请假申请失败!");
      }
      const idSql = `SELECT * FROM leaveapplication where id = ?`;
      db.query(idSql, [result.insertId], (error, res) => {
        if (error) return resp.err(error);
        if (res.length !== 1) return resp.err("获取用户信息失败！");
        resp.ok(res[0], "添加请假申请成功");
      });
    });
  } catch (error) {
    console.error("添加请假申请异常:", error);
    resp.err("添加请假申请失败: " + error.message);
  }
};

// 删除请假申请
exports.deleteLeave = (req, resp) => {
  try {
    const ids = req.body;

    // 验证必填字段
    if (!ids || !Array.isArray(ids) || ids.length === 0) {
      return resp.err("请假申请ID列表不能为空");
    }

    // 删除请假申请数据
    const deleteSql = "DELETE FROM leaveapplication WHERE id IN (?)";
    db.query(deleteSql, [ids], (err, result) => {
      if (err) {
        console.error("删除请假申请失败:", err);
        return resp.err("删除请假申请失败: " + err.message);
      }
      if (result.affectedRows === 0) {
        return resp.err("未找到要删除的请假申请!");
      }
      resp.ok(
        {
          deletedCount: result.affectedRows,
        },
        `成功删除${result.affectedRows}个请假申请`
      );
    });
  } catch (error) {
    console.error("删除请假申请异常:", error);
    resp.err("删除请假申请失败: " + error.message);
  }
};

// 修改请假申请信息
exports.updateLeave = (req, resp) => {
  try {
    const leaveInfo = req.body;

    // 验证是否提供了请假申请ID
    if (!leaveInfo.id) {
      return resp.err("请假申请ID不能为空");
    }

    // 更新请假申请数据
    const updateSql = "UPDATE leaveapplication SET ? WHERE id = ?";
    db.query(updateSql, [leaveInfo, leaveInfo.id], (err, result) => {
      if (err) {
        console.error("修改请假申请信息失败:", err);
        return resp.err("修改请假申请信息失败: " + err.message);
      }
      if (result.affectedRows === 0) {
        return resp.err("未找到该请假申请!");
      }

      // 查询更新后的请假申请信息
      const selectSql = "SELECT * FROM leaveapplication WHERE id = ?";
      db.query(selectSql, [leaveInfo.id], (err, rows) => {
        if (err) {
          console.error("查询更新后的请假申请信息失败:", err);
          return resp.err("查询更新后的请假申请信息失败: " + err.message);
        }
        if (rows.length === 0) {
          return resp.err("未找到该请假申请!");
        }

        resp.ok(rows[0], "修改请假申请信息成功");
      });
    });
  } catch (error) {
    console.error("修改请假申请信息异常:", error);
    resp.err("修改请假申请信息失败: " + error.message);
  }
};
